import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface User {
  id: string
  username: string
  nickname: string
  email: string
  phone: string
  avatar: string
  role: 'admin' | 'manager' | 'technician' | 'user'
  permissions: string[]
  department: string
  status: 'active' | 'inactive' | 'suspended'
  createTime: string
  lastLoginTime: string
}

export interface UserInfo {
  id: string
  username: string
  nickname: string
  email: string
  phone: string
  avatar: string
  role: string
  permissions: string[]
  department: string
  status: string
  createTime: string
  lastLoginTime: string
}

export interface LoginCredentials {
  username: string
  password: string
  rememberMe?: boolean
}

export interface AuthState {
  token: string | null
  user: User | null
  isAuthenticated: boolean
  permissions: string[]
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(uni.getStorageSync('token') || null)
  const user = ref<User | null>(null)
  const userInfo = ref<UserInfo | null>(null)
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)

  // 权限计算
  const permissions = computed(() => {
    if (!userInfo.value) return []
    return userInfo.value.permissions || []
  })

  const isAdmin = computed(() => userInfo.value?.role === 'admin')
  const isManager = computed(() => userInfo.value?.role === 'manager')
  const isTechnician = computed(() => userInfo.value?.role === 'technician')

  // 权限检查函数
  const hasPermission = (permission: string): boolean => {
    if (isAdmin.value) return true
    return permissions.value.includes(permission)
  }

  const hasRole = (role: string): boolean => {
    return userInfo.value?.role === role
  }

  const hasAnyRole = (roles: string[]): boolean => {
    if (!userInfo.value) return false
    return roles.includes(userInfo.value.role)
  }

  // 登录
  const loginAction = async (credentials: LoginCredentials): Promise<boolean> => {
    try {
      // 模拟API调用
      const response = await mockLogin(credentials)

      if (response.success) {
        token.value = response.data.token
        user.value = response.data.user
        userInfo.value = response.data.user

        // 保存token到本地存储
        uni.setStorageSync('token', token.value)
        uni.setStorageSync('userInfo', JSON.stringify(userInfo.value))
        if (credentials.rememberMe) {
          uni.setStorageSync('rememberMe', 'true')
        }

        return true
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 登出
  const logoutAction = async (): Promise<void> => {
    try {
      // 调用后端登出API
      token.value = null
      user.value = null
      userInfo.value = null

      // 清除本地存储
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('rememberMe')

      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/login/index'
      })
    } catch (error) {
      console.error('登出失败:', error)
    }
  }

  // 更新用户信息
  const updateUserInfo = async (userData: Partial<User>): Promise<boolean> => {
    try {
      // 模拟API调用
      if (userInfo.value) {
        const updatedUser = { ...userInfo.value, ...userData }
        userInfo.value = updatedUser
        user.value = updatedUser
        // 保存到本地存储
        uni.setStorageSync('userInfo', JSON.stringify(userInfo.value))
        return true
      }
      return false
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    }
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string): Promise<boolean> => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      return true
    } catch (error) {
      console.error('修改密码失败:', error)
      throw error
    }
  }

  // 刷新token
  const refreshToken = async (): Promise<boolean> => {
    try {
      // 模拟API调用
      const response = await mockRefreshToken()

      if (response.success) {
        token.value = response.data.token
        uni.setStorageSync('token', token.value)
        return true
      }
      return false
    } catch (error) {
      console.error('刷新token失败:', error)
      return false
    }
  }

  // 获取用户信息
  const fetchUserInfo = async (): Promise<boolean> => {
    try {
      if (!token.value) return false

      // 模拟API调用
      const response = await mockGetUserInfo()

      if (response.success) {
        userInfo.value = response.data
        user.value = response.data
        uni.setStorageSync('userInfo', JSON.stringify(userInfo.value))
        return true
      }
      return false
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return false
    }
  }

  // 初始化认证状态
  const initUser = async (): Promise<boolean> => {
    const savedToken = uni.getStorageSync('token')
    const savedUserInfo = uni.getStorageSync('userInfo')

    if (savedToken) {
      token.value = savedToken
      if (savedUserInfo) {
        userInfo.value = JSON.parse(savedUserInfo)
        user.value = JSON.parse(savedUserInfo)
        return true
      }
      return await fetchUserInfo()
    }
    return false
  }

  return {
    // 状态
    token,
    user,
    userInfo,
    isLoggedIn,
    permissions,

    // 计算属性
    isAdmin,
    isManager,
    isTechnician,

    // 方法
    loginAction,
    logoutAction,
    updateUserInfo,
    changePassword,
    refreshToken,
    fetchUserInfo,
    initUser,
    hasPermission,
    hasRole,
    hasAnyRole
  }
})

// Mock API functions
async function mockLogin(credentials: LoginCredentials): Promise<any> {
  await new Promise(resolve => setTimeout(resolve, 1000))

  // 模拟用户数据
  const mockUsers = {
    'admin': {
      id: '1',
      username: 'admin',
      nickname: '系统管理员',
      email: 'admin@meishen.com',
      phone: '13800138000',
      avatar: '/static/images/avatar-admin.png',
      role: 'admin' as const,
      permissions: ['*'],
      department: '技术部',
      status: 'active' as const,
      createTime: '2024-01-01 00:00:00',
      lastLoginTime: new Date().toLocaleString('zh-CN')
    },
    'manager': {
      id: '2',
      username: 'manager',
      nickname: '张经理',
      email: 'manager@meishen.com',
      phone: '13900139000',
      avatar: '/static/images/avatar-manager.png',
      role: 'manager' as const,
      permissions: ['device.view', 'device.manage', 'workorder.view', 'workorder.manage', 'alert.view', 'report.view'],
      department: '运营部',
      status: 'active' as const,
      createTime: '2024-01-02 00:00:00',
      lastLoginTime: new Date().toLocaleString('zh-CN')
    },
    'technician': {
      id: '3',
      username: 'technician',
      nickname: '李师傅',
      email: 'technician@meishen.com',
      phone: '13700137000',
      avatar: '/static/images/avatar-technician.png',
      role: 'technician' as const,
      permissions: ['device.view', 'workorder.view', 'workorder.process', 'alert.view'],
      department: '维护部',
      status: 'active' as const,
      createTime: '2024-01-03 00:00:00',
      lastLoginTime: new Date().toLocaleString('zh-CN')
    }
  }

  const user = mockUsers[credentials.username as keyof typeof mockUsers]

  if (user && credentials.password === '123456') {
    return {
      success: true,
      data: {
        token: 'mock-jwt-token-' + Date.now(),
        user: user
      },
      message: '登录成功'
    }
  } else {
    return {
      success: false,
      data: null,
      message: '用户名或密码错误'
    }
  }
}

async function mockRefreshToken(): Promise<any> {
  await new Promise(resolve => setTimeout(resolve, 500))
  return {
    success: true,
    data: {
      token: 'mock-jwt-token-' + Date.now()
    }
  }
}

async function mockGetUserInfo(): Promise<any> {
  await new Promise(resolve => setTimeout(resolve, 500))
  return {
    success: true,
    data: {
      id: '1',
      username: 'admin',
      nickname: '系统管理员',
      email: 'admin@meishen.com',
      phone: '13800138000',
      avatar: '/static/images/avatar-admin.png',
      role: 'admin',
      permissions: ['*'],
      department: '技术部',
      status: 'active',
      createTime: '2024-01-01 00:00:00',
      lastLoginTime: new Date().toLocaleString('zh-CN')
    }
  }
}